import threading

import cv2
import numpy as np
from paddleocr import PaddleOCR
from api.InternalConfig import npcGiveHeightBounds, npcGiveWidthBounds

# Paddleocr目前支持的多语言语种可以通过修改lang参数进行切换
# 例如`ch`, `en`, `fr`, `german`, `korean`, `japan`
# need to run only once to download and load model into memory
ocr = PaddleOCR(use_angle_cls=True, lang="ch", show_log=False)

# 锁,用于串行获得字
lock = threading.Lock()


def getWords(img):
    lock.acquire()

    # 将mat转ndarray
    convertedBytes = np.array(img)
    # 进行识别
    result = ocr.ocr(convertedBytes, cls=True)

    lock.release()

    return result


if __name__ == '__main__':
    img_path = R"F:\Project\DeepLearning\Game\material\dataset\fourMan\original\material\1710944308.6493754.jpg"
    img = cv2.imread(img_path)
    # 截取指定区域图像
    img = img[npcGiveHeightBounds[0]:npcGiveHeightBounds[1], npcGiveWidthBounds[0]:npcGiveWidthBounds[1]]
    result = getWords(img)
    for idx in range(len(result)):
        for word in result[idx]:
            print(word)

"""
    # 保存结果
    from PIL import Image

    result = result[0]
    image = Image.open(img_path).convert('RGB')
    boxes = [line[0] for line in result]
    txts = [line[1][0] for line in result]
    scores = [line[1][1] for line in result]
    im_show = draw_ocr(image, boxes, txts, scores, font_path='./fonts/simfang.ttf')
    im_show = Image.fromarray(im_show)
    im_show.save('result.jpg')
"""
